import 'package:amway_superapp_creator_plugin/analysis/zhuge_edit.dart';
import 'package:amway_superapp_creator_plugin/config/colors_config.dart';
import 'package:amway_superapp_creator_plugin/dialog/common_bottom_sheet.dart';
import 'package:amway_superapp_creator_plugin/dialog/loading_dialog.dart';
import 'package:amway_superapp_creator_plugin/routers/application.dart';
import 'package:amway_superapp_creator_plugin/routers/routes.dart';
import 'package:amway_superapp_creator_plugin/utils/image_pickasset_util.dart';
import 'package:amway_superapp_creator_plugin/utils/oss_util.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/edit/dy_model.dart';
import 'package:amway_superapp_creator_plugin/widget/diver.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:provider/provider.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../utils/toast_util.dart';

class InputDyInformation extends StatefulWidget {
  String dyCode = "";
  String image = "";

  InputDyInformation(this.dyCode, this.image);

  @override
  _InputDyInformationState createState() => _InputDyInformationState();
}

class _InputDyInformationState extends State<InputDyInformation> {
  FocusNode _focusNode = FocusNode();
  TextEditingController _dyController;

  @override
  void dispose() {
    super.dispose();
    _focusNode.dispose();
    _dyController.dispose();
  }

  bool isValuable = false;

  @override
  void initState() {
    _dyController = TextEditingController(text: widget.dyCode);
    ZhugeEditAnalysis.editPage(EditPageType.douyinPage);
    super.initState();
    if (widget.dyCode.isNotEmpty) {
      isValuable = true;
    } else {
      isValuable = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (_focusNode.hasFocus) _focusNode.unfocus();
      },
      child: Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            brightness: Brightness.light,
            backgroundColor: Colors.white,
            elevation: 0,
            centerTitle: true,
            title: Text(
              "录入抖音信息",
              style: TextStyle(
//                fontWeight: FontWeight.bold,
                  fontSize: ScreenUtil().setSp(20),
                  color: Color(0xff2C2C2C)),
            ),
            leading: InkWell(
                child: Container(
                    margin: EdgeInsets.only(left: ScreenUtil().setWidth(15)),
                    alignment: Alignment.centerLeft,
                    child: Text("取消",
                        style: TextStyle(
//                          fontWeight: FontWeight.bold,
                            fontSize: ScreenUtil().setSp(17),
                            color: Color(0xff0094A8)))),
                onTap: () {
                  Navigator.pop(context);
                }),
            actions: [
              Container(
                  alignment: Alignment.center,
                  child: Consumer<DyModel>(builder: (context, provide, child) {
                    return MaterialButton(
                        minWidth: 50.0,
                        onPressed: () {
                          // if (_dyController.text.isEmpty && isValuable) {
                          //   ToastUtils.showShortToast("已清空抖音号");
                          // }
                          ZhugeEditAnalysis.editKuaishouClickFinish(
                              "录入抖音信息页", true);
                          provide.setValue(
                              _dyController.text.isEmpty
                                  ? ""
                                  : _dyController.text,
                              widget.image,
                              _dyController.text.isEmpty && isValuable);
                          Navigator.pop(context, "input");
                        },
                        child: Text(
                          "完成",
                          style: TextStyle(
//                            fontWeight: FontWeight.bold,
                              fontSize: ScreenUtil().setSp(17),
                              color: Color(0xff0094A8)),
                        ));
                  }))
            ],
          ),
          body: Column(children: [
            Container(
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12),
                  boxShadow: [
                    BoxShadow(
                        color: ColorsConfig.c_14000000,
                        offset: Offset(0.0, 0.0), //阴影xy轴偏移量
                        blurRadius: 12.0, //阴影模糊程度
                        spreadRadius: 0.0 //阴影扩散程度
                        )
                  ]),
              margin: EdgeInsets.all(ScreenUtil().setSp(16)),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  _input("抖音号", "请输入您的抖音号", _dyController),
                  Divide(),
                  _input1("抖音名片（可选）", "上传", widget.image)
                ],
              ),
            ),
            Container(
              margin:
                  EdgeInsets.symmetric(horizontal: ScreenUtil().setWidth(16)),
              alignment: Alignment.centerLeft,
              child: Text("上传名片可帮助您更好的吸引顾客到抖音平台",
                  style: TextStyle(
                      color: ColorsConfig.c_4D000000,
                      fontSize: ScreenUtil().setSp(12))),
            )
          ])),
    );
  }

  RegExp emion = RegExp(
      "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]");
  RegExp chiness = RegExp(r"[\u4e00-\u9fa5]");
  RegExp space = RegExp("[^\\S]");

  Widget _input(String title, String hint, TextEditingController controller) {
    return Row(children: [
      Container(
        margin: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(16),
            ScreenUtil().setWidth(17),
            ScreenUtil().setWidth(13),
            ScreenUtil().setWidth(17)),
        child: Text(title,
            style: TextStyle(
                fontWeight: FontWeight.bold,
                color: Color(0xFF2C2C2C),
                fontSize: ScreenUtil().setSp(16))),
      ),
      Expanded(
          flex: 1,
          child: TextField(
            keyboardAppearance: Brightness.light,
            focusNode: _focusNode,
            keyboardType: TextInputType.text,
            inputFormatters: [
              FilteringTextInputFormatter.deny(emion),
              FilteringTextInputFormatter.deny(chiness),
              FilteringTextInputFormatter.deny(space),
              LengthLimitingTextInputFormatter(30) //限制长度
            ],
            controller: controller,
            style: TextStyle(fontSize: ScreenUtil().setSp(16)),
            decoration: InputDecoration(
                border: InputBorder.none,
                hintText: hint,
                hintStyle: TextStyle(
                    color: Color(0xB2000000), fontSize: ScreenUtil().setSp(16)),
                hintMaxLines: 1),
            maxLines: 1,
            onChanged: (text) {
              setState(() {
                widget.dyCode = text.trim();
              });
            },
          )),
      GestureDetector(
        onTap: () {
          _dyController.clear();
          setState(() {
            widget.dyCode = "";
          });
        },
        child: Container(
          padding: EdgeInsets.all(10),
          margin: EdgeInsets.only(right: ScreenUtil().setWidth(15)),
          child: _focusNode.hasFocus == true &&
                  widget.dyCode != null &&
                  widget.dyCode.length > 0
              ? Icon(
                  Icons.cancel,
                  size: ScreenUtil().setSp(22),
                  color: Colors.black45,
                )
              : Text(""),
        ),
      )
    ]);
  }

  Widget _input1(String title, String hint, String head) {
    return GestureDetector(
      child: Row(
        children: [
          Container(
            margin: EdgeInsets.fromLTRB(
                ScreenUtil().setHeight(16),
                ScreenUtil().setHeight(16),
                ScreenUtil().setHeight(20),
                ScreenUtil().setHeight(16)),
            child: Text(title,
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: const Color(0xFF2C2C2C),
                    fontSize: ScreenUtil().setSp(16))),
          ),
          Expanded(flex: 1, child: Text("")),
          Container(
            child: head == ""
                ? Text(
                    hint,
                    textAlign: TextAlign.end,
                    style: TextStyle(
                        color: Color(0x4D000000),
                        fontSize: ScreenUtil().setSp(16)),
                  )
                : Container(
                    child: Image.network(
                      head,
                      fit: BoxFit.fill,
                      width: ScreenUtil().setWidth(28),
                      height: ScreenUtil().setWidth(28),
                    ),
                    width: ScreenUtil().setWidth(35),
                    height: ScreenUtil().setWidth(35),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: ColorsConfig.c_F7F7F7,
                        border: Border.all(
                            color: ColorsConfig.c_d8d8d8,
                            width: ScreenUtil().setWidth(0.5)),
                        borderRadius: BorderRadius.circular(4),
                        boxShadow: [
                          BoxShadow(
                              color: ColorsConfig.c_14000000,
                              offset: Offset(0.0, 0.0), //阴影xy轴偏移量
                              blurRadius: 12.0, //阴影模糊程度
                              spreadRadius: 0.0 //阴影扩散程度
                              )
                        ])),
          ),
          Container(
              margin: EdgeInsets.only(right: ScreenUtil().setWidth(12)),
              child: Icon(
                Icons.keyboard_arrow_right,
                color: Color(0x4D2C2C2C),
                size: 24,
              ))
        ],
      ),
      onTap: () {
        if (widget.image.isNotEmpty) {
          _photo();
          return;
        }
        _choosePhoto();
      },
    );
  }

  void _photo() {
    showDialog(
        barrierDismissible: true,
        //是否点击空白区域关闭对话框,默认为true，可以关闭
        context: context,
        builder: (BuildContext context) {
          List<ItemMode> list = List<ItemMode>();
          list.add(
              ItemMode(label: '查看图片', color: ColorsConfig.c_396E75, size: 17));
          list.add(
              ItemMode(label: '重新选择', color: ColorsConfig.c_396E75, size: 17));
          return CommonBottomSheet(
            list: list,
            onItemClickListener: (index) async {
              Navigator.pop(context);
              switch (index) {
                case 0:
                  Map<String, dynamic> parameters = {
                    'image': widget.image,
                  };
                  Application.router.navigateTo(context, Routes.LOOK_BIG_IMAGE,
                      routeSettings: RouteSettings(arguments: parameters),
                      transition: TransitionType.cupertino);
                  break;
                case 2:
                  _choosePhoto();
                  break;
              }
            },
          );
        });
  }

  void _choosePhoto() {
    _focusNode.unfocus();
    pickAsset(context, RequestType.image, maxAssetsCount: 1, isCanEdite: false)
        .then((value) {
      if (value == null) {
        return;
      }
      showDialog(
        context: context,
        builder: (ctx) {
          return LoadingDialog(
            canceledOnTouchOutside: false,
            tipMsg: '正在上传中',
          );
        },
      );
      value.first.file.then((value) {
        OssHelper.getOssConfiguration().then((result) {
          Map<String, dynamic> ossMsg = {
            "accessKeyId": result.data['data']['accessKeyId'],
            "accessKeySecret": result.data['data']['accessKeySecret'],
            "expiration": result.data['data']['expiration'],
            "securityToken": result.data['data']['securityToken']
          };
          OssHelper.uploadToOss(value, ossMsg).then((value) {
            setState(() {
              widget.image = value;
              Application.router.pop(context);
            });
          });
        });
      });
    });
  }
}
